package com.xiao.common.util;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @Author xiaoxiaoping
 * @Date 2019/10/29
 */
public class HttpUtil {

    public static final String charset = "utf-8";

    public static final int JS_TIME_OUT = 6000;

    public HttpUtil() {
    }

    public static String getRest(String url, Map<String, Object> params) throws Exception {
        String resultStr = "";
        StringBuffer stringBuffer = new StringBuffer();
        String paramStr = null;
        String key;
        if (null != params) {
            Iterator iter = params.entrySet().iterator();

            for(int flag = 0; iter.hasNext(); ++flag) {
                Map.Entry entry = (Map.Entry)iter.next();
                Object value = entry.getValue();
                value = null == value ? "" : value;
                key = (String)entry.getKey();
                if (flag == 0) {
                    stringBuffer.append("?" + key + "=" + value);
                } else {
                    stringBuffer.append("&" + key + "=" + value);
                }
            }
        }

        paramStr = stringBuffer.toString();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url + paramStr);
        HttpConnectionParams.setConnectionTimeout(httpGet.getParams(), 60000);
        HttpConnectionParams.setSoTimeout(httpGet.getParams(), 60000);
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream inputStream = response.getEntity().getContent();
            key = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            while((key = reader.readLine()) != null) {
                buffer.append(key);
            }

            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
        }

        return resultStr;
    }

    public static String postRest(String url, Map<String, Object> params) throws Exception {
        String resultStr = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), 60000);
        HttpConnectionParams.setSoTimeout(httpPost.getParams(), 60000);
        List<NameValuePair> nvps = new ArrayList();
        String line;
        if (null != params) {
            Iterator iter = params.entrySet().iterator();

            while(iter.hasNext()) {
                Map.Entry entry = (Map.Entry)iter.next();
                line = (String)entry.getKey();
                Object value = entry.getValue();
                value = null == value ? "" : value;
                nvps.add(new BasicNameValuePair(line, value == null ? "" : value.toString()));
            }
        }

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream inputStream = response.getEntity().getContent();
            line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            while((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
        }

        return resultStr;
    }

    public static String postJson(String url, Map<String, Object> params) throws Exception {
        String resultStr = "";
        CloseableHttpClient client =HttpClients.createDefault();;
        HttpPost httpPost = new HttpPost(url);
        HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), 60000);
        HttpConnectionParams.setSoTimeout(httpPost.getParams(), 60000);
        String requestParam = toJsonWithGson(params);
        StringEntity entity = new StringEntity(requestParam, "UTF-8");
        Header header = new BasicHeader("Content-Type", "application/json;charset=UTF-8");
        entity.setContentType(header);
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream inputStream = response.getEntity().getContent();
            String line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            while((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
        }

        return resultStr;
    }

    public static String postJson(String url, Map<String, Object> params, Map<String, Object> headerParams) throws Exception{
        String resultStr = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(toJsonWithGson(params), Charset.forName("UTF-8"));
        httpPost.setEntity(se);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        String line;
        if (null != headerParams) {
            Iterator iter = headerParams.entrySet().iterator();

            while(iter.hasNext()) {
                Map.Entry entry = (Map.Entry)iter.next();
                line = (String)entry.getKey();
                String value = (String)entry.getValue();
                httpPost.addHeader(line, value);
            }
        }

        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream inputStream = response.getEntity().getContent();
            line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            while((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }

            System.out.println("POST方式结果：" + resultStr);
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
        }

        return resultStr;
    }

    public static String toJsonWithGson(Object object) {
        String jsonStr = JSONObject.toJSONString(object);
        return jsonStr;
    }

}
